package warden;

import log.Logger;
import log.NullLogger;
import philosoph.Philosoph;

public class SimpleEatTimeWarden<T extends Philosoph> implements EatTimeWarden<T> {

	private Logger logger;
	private int timeout;

	public SimpleEatTimeWarden(int timeout) {
		this(new NullLogger(), timeout);
	}

	public SimpleEatTimeWarden(Logger logger, int timeout) {
		this.timeout = timeout;
		this.logger = logger;
	}

	@Override
	public void watchOver(final T t) {
		Thread th = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					t.eat();
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
					// do nothing
				}
			}
		});
		th.start();
		this.stop(th, t);
	}

	@SuppressWarnings("deprecation")
	private void stop(Thread th, T t) {
		boolean interrupted = false;
		try {
			th.join(this.timeout);
		} catch (InterruptedException e) {
			interrupted = true;
		}
		if (th.isAlive()) {
			th.interrupt();
			this.logger.log(-1, "Philosoph Nr. " + String.format("%4d", t.hashCode()) + " has been removed from the table.");
		}
		try {
			th.join(timeout);
		} catch (InterruptedException e) {
			interrupted = true;
		}
		if (th.isAlive()) {
			th.stop();
			this.logger.log(-1, "Philosoph Nr. " + String.format("%4d", t.hashCode()) + " has been removed from the table forcefully.");
		}
		if (interrupted) Thread.currentThread().interrupt();
	}

}
